﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using G.Navigate;
using System.Collections.Generic;
using System.Linq;

namespace G.Controls
{
    public class PageListBox : GListBox
    {
        public static readonly DependencyProperty PageCountProperty = DependencyProperty.Register("PgaeCount", typeof(int), typeof(PageListBox), null);
        public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(int), typeof(PageListBox), new PropertyMetadata(20));
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(PageListBox), null);
        public ICommand Command
        {
            get
            {
                return this.GetValue(CommandProperty) as ICommand;
            }
            set
            {
                this.SetValue(CommandProperty, value);
            }
        }
        public int PgaeCount
        {
            get { return (int)this.GetValue(PageListBox.PageCountProperty); }
            set { this.SetValue(PageListBox.PageCountProperty, value); }
        }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize
        {
            get
            {
                return (int)this.GetValue(PageSizeProperty);
            }
            set
            {
                this.SetValue(PageSizeProperty, value);
            }
        }

        public PageListBox()
            : base()
        {
            this.DefaultStyleKey = typeof(PageListBox);
        }


        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            if (ScrollViewer != null)
            {
                PropertyValueChangedNotify.Create("VerticalOffset", ScrollViewer).PropertyValueChanged += new PropertyValueChangedHandle(PageListBox_PropertyValueChanged);
            }
        }

        void PageListBox_PropertyValueChanged(DependencyObject d, PropertyValueChangedEventArgs e)
        {
            //ExtentHeight的值其实就是表示ScrollViewer一共有多少项，而一般如果滑到低的话VerticalOffset+ViewportHeight和ExtentHeight相差会小于1，也就是滑到最后一条记录
            double diff = (ScrollViewer.ExtentHeight - ScrollViewer.VerticalOffset - ScrollViewer.ViewportHeight);
            if (ScrollViewer.ScrollableHeight > 0 && diff < 1)
            {
                LoadingData();
            }
        }
        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonUp(e);

        }
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

        }
        public event PageEventHandle BeginLoadData;
        private bool isLoading = false;

        bool hasNextPage = true;
        protected int NextPage
        {
            get
            {
                object obj = this.OwnerPage.ReadFromState(this.Name + "_NextPage");
                if (obj == null)
                {
                    this.OwnerPage.SaveToState(this.Name + "_NextPage", 1);
                    obj = 1;
                }
                return (int)obj;
            }
            set
            {
                this.OwnerPage.SaveToState(this.Name + "_NextPage", value);
            }
        }

        public override void EnableTombstoneListBox<T>(GBasePage page)
        {
            base.EnableTombstoneListBox<T>(page);
            this.IsEnablePageListBox = true;
            if (this.ItemsSource == null)
                this.LoadFirstPage();
        }

        /// <summary>
        /// 取消分页功能
        /// </summary>
        public void CancelPageListBox()
        {
            this.IsEnablePageListBox = false;
        }
        //private string Key;
        public bool IsEnablePageListBox { get; private set; }
        /// <summary>
        /// 加载首页
        /// </summary>
        private void LoadFirstPage()
        {
            this.NextPage = 1;
            this.LoadingData();
        }
        protected override void LoadingData()
        {
            if (IsEnablePageListBox && !isLoading && hasNextPage)
            {
                base.LoadingData();
                isLoading = true;
                PageEventArgs e = new PageEventArgs();
                e.PageSize = this.PageSize;
                e.PageNum = NextPage;
                if (this.Command != null)
                    Command.Execute(e);
                else if (BeginLoadData != null)
                    BeginLoadData(this, e);
            }
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datas"></param>
        public override void LoadData<T>(IEnumerable<T> datas)
        {
            base.LoadData<T>(datas);
            isLoading = false;
            //PhoneApplicationPageHelp.GetBasePage().UnregisterLoading();
            if (datas != null)
                NextPage++;
            else
                this.CancelPageListBox();

            if (datas != null && datas.Count() < this.PageSize)
                this.CancelPageListBox();
        }

        public override void ClearItems()
        {
            base.ClearItems();
            NextPage = 1;
            isLoading = false;
            hasNextPage = true;
        }

    }
    public delegate void PageEventHandle(object sender, PageEventArgs e);
    //public delegate void PageListBoxLoadDataHandle<T>(IEnumerable<T> datas);
    public class PageEventArgs : EventArgs
    {
        internal Action<bool> IsLoadedChangedCallBack;
        public int PageNum { get; internal set; }
        public int PageSize { get; internal set; }
        private bool isLoaded;
        /// <summary>
        /// 是否启用分页
        /// </summary>
        public bool IsLoaded
        {
            get
            {
                return isLoaded;
            }
            set
            {
                if (isLoaded != value)
                {
                    isLoaded = value;
                    if (IsLoadedChangedCallBack != null)
                        IsLoadedChangedCallBack(value);
                }
            }
        }
    }
}
